package top.zackyoung.demo.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import top.zackyoung.demo.entity.User;

import java.util.List;

/**
 * @author: ZackYoung
 * @time: 2020/9/14
 */

public interface UserRepository extends JpaRepository<User,Long>,CrudRepository<User, Long> {

    /**
     * 根据用户名查询
     * @param name 用户名
     * @return 返回
     */
    @Query("select t from User t where t.userName = :name")
    User findByUserName(@Param("name") String name);

    /**
     * 查询全部
     * @return 返回
     */
    @Query("select t from User t")
    List<User> find();

    /**
     * 删除  必须加@Modifying和@Transactional
     * @param id 用户id
     * @return 返回
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query("delete from User u where u.id=:id")
    int deleteUserById(@Param("id") Long id);

    /**
     * 自定义更新操作
     * @param id 用户id
     * @param name  用户名
     * @return  返回int
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query("update User set userName=:name where id=:id")
     int updateByUserId(@Param("id")Long id,@Param("name")String name);

    /**
     * 自定义添加操作
     * @param id    用户id
     * @param name  用户名
     * @return  返回int
     */
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query(value = "insert into user (id,user_name) values(?1,?2)", nativeQuery = true)
    int add(Long id, String name);

    /**
     * 分页功能
     * @param roleId    角色id
     * @param pageable  分页
     * @return  返回page
     */
    Page<User> findByRoleId(Long roleId, Pageable pageable);
}
